package com.wumao.controller.admin;

import com.wumao.pojo.Type;
import com.wumao.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @author Gaowumao
 * @Decripted
 * @Email none-j@qq.com
 * @create 2021-04-15 20:26
 */
@Controller
@RequestMapping("/admin")
public class TypeController {

    @Autowired
    private TypeService typeService;

    @RequestMapping("/types")
    /*分页，每页十条，通过id来排序。并且是降序*/
    public String types(@PageableDefault(size = 10,sort = {"id"},
            direction = Sort.Direction.DESC) Pageable pageable, Model model){
        model.addAttribute("page",  typeService.listType(pageable)) ;

        return "admin/types";
    }


    @RequestMapping("/types/input")
    public String input(){
        return "admin/type-input";
    }

    @RequestMapping("/types/{id}/input")
    public String editInput(@PathVariable Long id, Model model){
        model.addAttribute("type",typeService.getType(id));
        return "admin/type-input";
    }

    @RequestMapping("/add")
    public String add(Type type, RedirectAttributes attributes){

//        Type type1 = typeService.getTypeByname(type.getName());
//        if (type1 != null){
//            result.rejectValue("name","nameError","分类不能重复添加");
//        }

        Type t = typeService.addType(type);
        if (t == null){
            attributes.addFlashAttribute("message","操作失败");
        }else{
            attributes.addFlashAttribute("message","操作成功");
        }
        return "redirect:/admin/types";
    }
    @RequestMapping("/add/{id}")
    public String update(Type type,@PathVariable Long id ,RedirectAttributes attributes){

//        Type type1 = typeService.getTypeByname(type.getName());
//        if (type1 != null){
//            result.rejectValue("name","nameError","分类不能重复添加");
//        }

        Type t = typeService.updateType(id,type);
        if (t == null){
            attributes.addFlashAttribute("message","更新失败");
        }else{
            attributes.addFlashAttribute("message","更新成功");
        }
        return "redirect:/admin/types";
    }

    @RequestMapping("/types/{id}/delete")
    public String delete(@PathVariable Long id,RedirectAttributes attributes){
        typeService.deleteType(id);
        attributes.addFlashAttribute("message","删除成功");
        return "redirect:/admin/types";
    }
}
